import { defineStore } from 'pinia';
import { useStorage } from '@vueuse/core';
import {
  login as apiLogin,
  logout as apiLogout,
  LoginData,
  getProfile,
} from '@/api/admin';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { AdminState } from './types';
import useAppStore from '../app';

const useAdminStore = defineStore('admin', {
  state: (): AdminState => ({
    id: undefined,
    name: undefined,
    username: undefined,
    nickname: undefined,
    avatar: undefined,
    full_avatar: undefined,
    email: undefined,
    phone: undefined,
    remark: undefined,
    role: '', // 根据角色判断权限
    role_routes: [], // 判断路由权限
    count_unreadmsg: 0, // 未读消息
    options: {}, // 配置
  }),

  getters: {
    adminInfo(state: AdminState): AdminState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<AdminState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

    // Get user's information
    async profile() {
      const res = await getProfile();

      this.setInfo(res.data);

      // 未读消息
      const countUnreadmsg = useStorage('count_unreadmsg', 0);
      countUnreadmsg.value = res.data.count_unreadmsg;
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await apiLogin(loginForm);
        setToken(res.data.token);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },

    // Logout
    async logout() {
      try {
        await apiLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useAdminStore;
